﻿using Microsoft.IdentityModel.Logging;
using PLCS.App.Shared.Common;
using PLCS.Application.Contracts.EquipmentApp.Dtos;
using PLCS.Client.Service.Client;
using PLCS.Domain.Shared.Enums;
using RestSharp;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace PLCS.App.Shared.Views.UserControls.Chlidren;

/// <summary>
/// TurnoverMachine.xaml 的交互逻辑
/// </summary>
public partial class TurnoverMachine : UserControl
{
    #region Properties

    //左边框
    private Rectangle left = new();

    //右边框
    private Rectangle right = new();

    //Webapi客户端
    public HttpRestClient restClient = new();

    private RequestParam requestParam;
    private Brush bg;
    private Brush tempbg;

    /// <summary>
    /// 名称
    /// </summary>
    public string SName
    {
        get { return (string)GetValue(SNameProperty); }
        set { SetValue(SNameProperty, value); }
    }

    public static readonly DependencyProperty SNameProperty =
        DependencyProperty.Register("SName", typeof(string), typeof(TurnoverMachine), new PropertyMetadata("F101"));

    #endregion Properties

    #region Contructor

    public TurnoverMachine()
    {
        InitializeComponent();
        Background = Background ?? Brushes.Transparent;
        bg = Background;
        Background = Brushes.Transparent;
        Cursor = Cursors.Hand;
        SizeChanged += TurnoverMachine_SizeChanged;
        UIChange();
    }

    #endregion Contructor

    #region Event

    private void TurnoverMachine_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        //画两个工位组合在一起
        ToolTip = $"翻转设备:{SName}";
        LayoutCanvas.Children.Clear();//when size change then clear canvas's children.
        //左侧边
        left = new Rectangle();
        left.Height = LayoutCanvas.ActualHeight;
        left.Width = 5;
        left.Fill = bg == Brushes.Transparent ? Brushes.Gray : bg;
        LayoutCanvas.Children.Add(left);
        //右侧边
        right = new Rectangle();
        right.Height = 5;
        right.Width = LayoutCanvas.ActualWidth;
        right.Fill = bg == Brushes.Transparent ? Brushes.Gray : bg;
        right.Margin = new Thickness(3, LayoutCanvas.ActualHeight - 3, 0, 0);
        LayoutCanvas.Children.Add(right);
    }

    #endregion Event

    #region UIChange

    /// <summary>
    /// 更改UI
    /// </summary>
    private async void UIChange()
    {
        await Dispatcher.BeginInvoke(new Action(async () =>
        {
            try
            {
                while (true)
                {
                    Background = Brushes.Transparent;
                    // SName 为空 跳出
                    if (string.IsNullOrWhiteSpace(SName))
                    {
                        await Task.Delay(TimeSpan.FromSeconds(5));
                        continue;
                    }
                    requestParam = new RequestParam(Method.Get, $"equipment/bySName?name={SName}");
                    var apiResponse = await restClient.ExecuteAsync<EquipmentDto>(requestParam);
                    var model = apiResponse.Data;
                    if (model == null)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(5));
                        continue;
                    }
                    //设备状态颜色变化
                    switch (model.Status)
                    {
                        case DeviceStatus.空闲:
                            tempbg = Brushes.DimGray;
                            break;

                        case DeviceStatus.忙碌:
                            tempbg = new SolidColorBrush(Color.FromRgb(0, 230, 118));// "#ABFF33";
                            break;

                        case DeviceStatus.故障:
                            tempbg = new SolidColorBrush(Color.FromRgb(255, 61, 0));
                            break;

                        default:
                            tempbg = Brushes.Transparent;
                            break;
                    }
                    if (this.tempbg.ToString() != bg.ToString())
                    {
                        bg = tempbg;
                        //边框颜色变化
                        right.Fill = left.Fill = bg == Brushes.Transparent ? Brushes.Gray : bg;
                    }
                    ////是否有货变化
                    //if (model.ContainStation == null) continue;
                    //requestParam = new RequestParam(Method.Post, $"station?bySName={model.ContainStation.Split(";")[0]}");
                    //var apiResponseSta = restClient.Execute<StationDto>(requestParam);
                    //var modelSta = apiResponseSta.Data;
                    //if (modelSta == null) continue;
                    // if (model.HaveStatus != HaveStatus) HaveStatus = model.HaveStatus;
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch (Exception ex)
            {
                ex = new Exception($"翻转设备{SName}更改界面方法发生错误：{ex.Message}");
                //LogHelper.LogExceptionMessage(ex);
                await Task.Delay(5000);
            }
        }), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
    }

    #endregion UIChange

    #region Animation

    /// <summary>
    /// 旋转
    /// </summary>
    /// <param name="rotatevalue"></param>
    public void RotateAnimation(double initvalue, double rotatevalue)
    {
        AnimationHelper.AngleRotateAnimation(this, initvalue, rotatevalue, 1, TimeSpan.FromSeconds(10));
    }

    #endregion Animation
}